//
//  CCTopicSegmentControl.swift
//  WangYiNews
//
//  Created by lanou3g on 16/1/19.
//  Copyright © 2016年 lanou3g. All rights reserved.
//


class SegmenItem:UIButton{
   private let titleFont = UIFont.systemFontOfSize(17)
   private let titleColor = UIColor.darkGrayColor()
   private let seletedFont = UIFont.systemFontOfSize(20)
   private let seletedColor = UIColor.yellowColor()
   override func setTitle(title: String?, forState state: UIControlState) {
        var attribu = [String:AnyObject]()
        attribu[NSFontAttributeName] = self.titleFont
        attribu[NSForegroundColorAttributeName] = self.titleColor
        let attribuTitle = NSAttributedString(string:title!, attributes:attribu)
        self.setAttributedTitle(attribuTitle, forState:.Normal)
        var seletedAttribu = [String:AnyObject]()
        seletedAttribu[NSFontAttributeName] = self.seletedFont
        seletedAttribu[NSForegroundColorAttributeName] = self.seletedColor
        let seletedTitle = NSAttributedString(string:title!, attributes:seletedAttribu)
        self.setAttributedTitle(seletedTitle, forState:.Selected)
    }
}

// 一些尺寸的全局常量
// 透明遮盖的宽度
let kLeftMagin:CGFloat = 30
let kItemWidth:CGFloat = 80

// 透明遮盖的透明度
let kAlpha:CGFloat  = 0.78

class CustomSegmentControl: UIView{
    
    var seletedAction:((index:Int)->())?
    var titles:[String]?
    var curentIndex:Int = 0
    
    var itemWith : CGFloat{
        return self.bounds.size.width / CGFloat(self.numberOfImtems)
    }
    
    private var segmenItems:[SegmenItem]
    
    //    一些计算属性
    private var height:CGFloat{
        return self.frame.size.height
    }
    
    private var width:CGFloat{
        return self.frame.size.width
    }
    
    private var numberOfImtems:Int{
        if let count = self.titles?.count{
            return count
        }
        return 0
    }

//    外部接口
    convenience init(items:[String],seletedAction:(index:Int)->()){
        self.init()
        self.seletedAction = seletedAction
        self.titles = items
        self.curentIndex = 0
        self.scrollView.contentOffset = CGPoint.zero
        self.setupSegItems()
    }
    
   private func setupSegItems(){
        var array = [SegmenItem]()
        var i = 0
        for title in self.titles!{
            let item = SegmenItem()
            if i == 0 {item.selected = true}
            item.tag = i++
            item.setTitle(title, forState:.Normal)
            item.addTarget(self, action:"selectItem:", forControlEvents:.TouchUpInside)
            self.scrollView.addSubview(item)
            var preItem : UIView
            if i == 1{
                preItem = self
            }else{
                preItem = array[i-2]
            }
            constractItem(item,preItem:preItem)
            array.append(item)
            print(array)
            self.setNeedsLayout()
        }
        self.segmenItems = array
    }
    
    private func constractItem(item:SegmenItem,preItem:UIView){
        let i = item.tag
        item.snp_makeConstraints(){[weak self] in
            $0.width.equalTo(self!).dividedBy(self!.numberOfImtems)
            $0.centerY.equalTo(self!)
            if i == 0{
                $0.left.equalTo(self!)
            }else{
                $0.left.equalTo(preItem.snp_right)
            }
        }
    }
    
    func updateIndex(index:Int){
        let item = self.segmenItems[index]
        self.selectItem(item)
    }
    
//    点击item时的动作
    func selectItem(item:SegmenItem){
        if item.tag == self.curentIndex {return}
        self.segmenItems[self.curentIndex].selected = false
        item.selected = true
        self.changeContenOfSet(item)
        self.curentIndex = item.tag
        self.seletedAction!(index: item.tag)
    }
    
    private func changeContenOfSet(item:SegmenItem){
        var x = item.frame.midX - self.frame.midX
        if x < 0  {  x = 0 }
        self.scrollView.setContentOffset(CGPoint(x:x,y:0), animated:true)
    }
    
//    view上的子控件
    private lazy var scrollView:UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.bounces = false
        scrollView.scrollEnabled = false
        self.addSubview(scrollView)
        scrollView.snp_makeConstraints(){[weak self] in
            $0.size.equalTo(self!)
            $0.center.equalTo(self!)
        }
        return scrollView
    }()
//    两边的透明遮盖
   private lazy var leftView:UIView = {
        let view = UIView()
    view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(kAlpha)
        self.addSubview(view)
        return view
    }()
   private lazy var ringhtView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
        self.addSubview(view)
        return view
    }()
    
//    初始化方法
   override init(frame: CGRect) {
        self.segmenItems = [SegmenItem]()
        super.init(frame:frame)
        self.addSubview(self.scrollView)
        self.addSubview(self.leftView)
        self.addSubview(self.ringhtView)
        self.layoutSubviews()
    }
    
   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.setupScorollView()
    }
    
    private func setupScorollView(){
//       self.scrollView.frame = self.bounds
//        let count = self.numberOfImtems
//        self.scrollView.contentSize = CGSize(width:kItemWidth * CGFloat(count), height:0)
//        var i:CGFloat = 0
//        for subView in self.scrollView.subviews{
//                if let item = subView as? SegmenItem{
////                    item.frame = CGRect(x:kItemWidth * i, y:0, width:kItemWidth, height:self.height)
////                    print(item.frame)
//                    item.frame = self.bounds
//                    item.contentMode = .Center
//                    i += 1.0
//                }
//        }
    }
    
    
    
}
